/**
 * 获取代理的地区
 */
var AnalysisBaiduAd = require("./AnalysisBaiduAd.js");
var RegionList = require("../common/RegionList.js");


module.exports = new ProxyRegion();
function ProxyRegion(){
	//单例模式
    if(typeof arguments.callee.instance === "object"){
        return arguments.callee.instance;
    }

    this.list = [];
	consume(this);

    arguments.callee.instance = this;
}

function consume(that){
	setInterval(
		function(){
			var item = that.list.pop();
			if(item==undefined || item.length!=2){
				return false;
			}
			var body = item[1];
			var ep = item[0];
			if(typeof ep.emit!='function'){
				return false;
			}

			var region = that.analysisRegion(body);
	        if(!isNaN(region.regionId)){
		        region = {};
			}
			ep.emit("end", region);
		}
	,100);
}


ProxyRegion.prototype.start = function(ep,body){
		this.list.push([ep,body]);
		setTimeout(function(){
			ep.emit("timeout");
		},10000)
}


ProxyRegion.prototype.analysisRegion= function(body){
    try{
        var adinfo = AnalysisBaiduAd.analysis(body);
        var adlist = adinfo.ad;

        //计算广告中包含某些地区的次数
        var hits = {};
        var hitsProvince = {};

        for(var i in adlist ){
            var desc = adlist[i].desc;
            var title = adlist[i].title;

            for(var regionId in RegionList){
                if( desc.indexOf(RegionList[regionId].shortname)>=0 || title.indexOf(RegionList[regionId].shortname)>=0 ){
                    var pid = RegionList[regionId].pid;
                    //国家级别的跳过
                    if(pid==0){
                        continue;
                    }

                    var provinceRegion = this.province(RegionList[regionId]);
                    if(provinceRegion.id==undefined){
                        continue;
                    }
                    if(hitsProvince[provinceRegion.id]==undefined){
                        hitsProvince[provinceRegion.id]=0;
                    }
                    hitsProvince[provinceRegion.id]++;
                }
            }
        }
        console.log(hitsProvince);
        var moreHitregionId = 0;
        var moreHit = 0;
        for(var regionId in hitsProvince){
            if(hitsProvince[regionId]>moreHit){
                moreHit = hitsProvince[regionId];
                moreHitregionId = regionId;
            }
        }

        var region = {};
        if(moreHitregionId>0){
            region = RegionList[moreHitregionId];
        }
    }catch (err){
        console.log(err);
        region = {};
    }
    return region;
}

ProxyRegion.prototype.province = function(region){
    var regionsArr = [];
    regionsArr.unshift(region);
    for(var i=0;i<=10;i++){
        if(region.pid==0){
            break;
        }
        var region = RegionList[region.pid];
        regionsArr.unshift(region);
    }
    //国家 > 省份 > 市 ; 市在第三级，所以应该是数组标为 2
    if(regionsArr.length>2){
        region = regionsArr[1];
    }else{
        region = {};
    }
    return region;
}